package cn.lixin.org.service.impl;

import cn.lixin.basic.exception.BusinessException;
import cn.lixin.basic.service.impl.BaseServiceImpl;
import cn.lixin.org.domain.Employee;
import cn.lixin.org.domain.Shop;
import cn.lixin.org.mapper.EmployeeMapper;
import cn.lixin.org.mapper.ShopMapper;
import cn.lixin.org.service.IEmployeeService;
import cn.lixin.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private IEmployeeService employeeService;


    @Override
    public void Settlement(Shop shop){
        /*
            校验：两次密码是否相同 前端校验容易破防
         */
        Employee admin = shop.getAdmin(); // 获取shop中的admin
        if (!admin.getPassword().equals(admin.getComfirmPassword())){// 两次密码不相同
            throw new BusinessException("两次密码不相同");
        }

         /*
            校验：账号是否被注册了
         */
        String username = admin.getUsername();
        Employee employee = employeeMapper.loadByUser(username); // 根据填写的名字查询是否有对应的emp（三个查询内容）
        if(employee != null){
         throw new BusinessException("用户名重复");
        }
         /*
            入驻：
         */
        //employeeMapper.save(admin);// 先保存admin 获取自增id shop_id 不能为空
        employeeService.save(admin); // 因为这里保存了员工信息，在Logininfo中也需要保存
        shop.setAdmin(admin); // 重新设置一下shop中的admin信息（有admin自增id）
        shopMapper.save(shop); // 将重新设置的shop保存（有admin自增id）
        admin.setShop_id(shop.getId()); // 获取店铺的id，赋值给admin的Shop_id
        employeeMapper.update(admin); // 修改admin信息

    }

    @Override
    public void SendEmail(String email) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true,"utf-8");
        helper.setFrom("838255256@qq.com");
        helper.setTo(email);
        helper.setText("你的审核已经通过，恭喜你店铺入驻成功！");
        helper.setSubject("关于店铺审核详细audit");
        helper.addAttachment("嘿嘿嘿.jpg",new File("C:\\Users\\Lx\\Pictures\\imgs\\girls.jpg"));
        javaMailSender.send(message);
    }
}
